Strict

#TEXT_FILES="*.txt|*.xml|*.json|*.lua"

Import monkeylua

Function Main:Int()
	' create a new instance of LuaState (usually only need one per application)
	Local ls:LuaState = New LuaState
	
	' create a new instance of TestFunc and use the Register method to assign it to the key "myfunc" in the global table
	New TestFunc().Register(ls, "myfunc")
	
	' create a new instance of TestObject to be used in our Lua callbacks
	Local testobj:TestObject = New TestObject("Hello World!")
	
	' push the test object onto the stack
	ls.PushMonkeyObject(testobj)
	
	' assign the test object to the key "testobj" in the global table (which then pops testobj off the stack)
	ls.SetGlobal("testobj")
	
	' call our test lua script and print the error message if one was returned
	If ls.DoFile("data/test.lua") <> LUA_OK Then Print ls.ToString(-1)
	
	' close the lua state (usually do this once at the end of the application)
	ls.Close()
	
	' one last test to show that the field was indeed changed
	Print "testobj.testfield="+testobj.testfield
	
	Return 0
End

Class TestObject
	Field testfield:String
	Method New(val:String)
		Self.testfield = val
	End
End

' this class acts as a callback so that it can be used in Lua scripts
Class TestFunc Extends MonkeyFunction
	' this is the function that will be called
	Method Func:Int(state:LuaState)
		Print "TestFunc: Entering"
		
		' we take the monkey object from the the first index of the stack (the first argument)
		Print "TestFunc: Calling ToMonkeyObject(1)"
		Local obj:Object = state.ToMonkeyObject(1)
		
		' try to cast it to a TestObject
		Print "TestFunc: Casting"
		Local tob:TestObject = TestObject(obj)
		
		' print out the current value of "testfield" which should be "Hello World!" on the first call
		Print "TestFunc: Printing testfield"
		Print tob.testfield
		
		Print "TestFunc: Returning"
		Return 0
	End
End
